/**
 * @author hewei
 * @version 1.0
 * @description: 390. 消除游戏
 * @date 2022/8/1 15:05
 */

public class LastRemaining {

    public static void main(String[] args) {
        LastRemaining lastRemaining = new LastRemaining();
        System.out.println(lastRemaining.lastRemaining(5));
    }

    public int lastRemaining(int n) {
        int l = 1;
        int count = n;
        int temp = 0;
        boolean flag = true;
        while (count > 1) {
            int a = (int) Math.pow(2, temp);
            if (flag) l += a;
            else l += count % 2 == 0 ? 0 : a;
            ++temp;
            count /= 2;
            flag = !flag;
        }
        return l;
    }
}
